import { reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useMailVerifyStore } from '@/store/mail-verify'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { useYup } from '@/plugins/yup'
import { SEND_EMAIL_CODE_TYPE } from '@/constant'
import API from '@/http'

export function useMailVerify() {
  const { open } = usePopupMessageStore()
  const { isVerifying, newVerifiedMail } = storeToRefs(useMailVerifyStore())
  const { startCountdown } = useMailVerifyStore()
  const { userData } = storeToRefs(useAccountStore())
  const yup = useYup()
  const verifyStatus = ref(userData.value.is_bind_email)

  // 切換區域 「輸入信箱區」「改變已驗證信箱區」「確認驗證碼區」
  const inputEmail = ref(true)
  const changeVerifiedMail = ref(verifyStatus.value)
  const confirmVerify = ref(false)

  const mailVerifyError = ref('')
  const confirmVerifyError = ref('')

  const form = reactive({
    mail: {
      value: userData.value?.email,
      error: '',
      check: false,
      schema: yup.string().email().required(),
    },
    code: {
      value: '',
      error: '',
      check: false,
      schema: yup
        // .number()
        // .test('len', { key: 'yup.number.length', values: { num: 6 } }, (value) => value && value.toString().length === 6)
        .string()
        .length(6)
        .typeError($t('yup.number.value'))
        .required($t('yup.number.value')),
    },
  })

  const resetForm = (...keys) => {
    keys.forEach((key) => {
      form[key].error = ''
      form[key].check = false
    })
  }

  const resetError = () => {
    mailVerifyError.value = ''
    confirmVerifyError.value = ''
  }

  // 傳送信箱驗證碼
  async function sendMailVerificationCode(type) {
    try {
      if (isVerifying.value) return
      const data = { email: form.mail.value, type } // type: 1 綁定信箱, 2 換信箱綁定
      await API.Auth.sendEmailCode({ data })
      startCountdown() // 倒數計時
      inputEmail.value = false
      confirmVerify.value = true
    } catch (e) {
      console.log('後端傳錯：', e)
      isVerifying.value = false
      mailVerifyError.value = e.message
    }
  }

  // 驗證信箱的驗證碼是否正確
  async function validateEmail(type) {
    try {
      const data = {
        email: form.mail.value,
        code: Number(form.code.value),
        type: type, // 1 綁定信箱, 2 換信箱綁定
      }
      await API.Auth.validateEmail({ data })
      open($t('common.setSuc'))

      if (data.type === SEND_EMAIL_CODE_TYPE.BIND) {
        newVerifiedMail.value = form.mail.value
        console.log('新的驗證信箱:', newVerifiedMail.value)
        userData.value.email = form.mail.value
      }
      userData.value = { ...userData.value, email: form.mail.value }

      resetForm('code')
      resetError()

      inputEmail.value = true
      changeVerifiedMail.value = true
      confirmVerify.value = false
      isVerifying.value = false
    } catch (e) {
      confirmVerifyError.value = e.message
    }
  }

  return {
    sendMailVerificationCode,
    validateEmail,
    resetForm,
    resetError,
    form,
    mailVerifyError,
    confirmVerifyError,
    verifyStatus,
    inputEmail,
    changeVerifiedMail,
    confirmVerify,
  }
}
